<?php

namespace support;

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class KuaidiBird
{
    protected $eBusinessId = '';

    protected $apiKey = '';

    protected $isDebug = false;

    public function __construct($eBusinessId, $apiKey)
    {
        $this->eBusinessId = $eBusinessId;
        $this->apiKey = $apiKey;
    }

    public function setDebug()
    {
        $this->isDebug = true;
        return $this;
    }

    public function doRequest($requestType, $requestData)
    {
        if ($this->isDebug) {
            $url = 'http://183.62.170.46:8081/api/dist';
        } else {
            $url = 'https://api.kdniao.com/api/OOrderService';
        }

        $client = new Client(['base_uri' => $url]);

        $res = $client->post('', [
            RequestOptions::FORM_PARAMS => http_build_query($this->buildParams($requestData, $requestType)),
        ]);

        return $res;
    }

    public function buildParams($requestData, $requestType)
    {
        $originalRequestData = $requestData;
        $requestData = urlencode($requestData);
        $requestData = str_replace('+', '', $requestData);


        $sign = md5($originalRequestData . $this->apiKey);
        $sign = urlencode(base64_encode($sign));

        $data = ['RequestType' => $requestType, 'EBusinessID' => $this->eBusinessId, 'RequestData' => $requestData, 'DataSign' => $sign, 'DataType' => 2];

        $strs = [];
        foreach ($data as $key=>$value) {
            $strs[] = "$key=$value";
        }

        return $strs;
    }
}